﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace BatchRename
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
            ddlFilter.SelectedIndex = 0;
            ddlFilter.SelectedIndexChanged += ddlFilter_SelectedIndexChanged;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            ddlDir.Text = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        }

        private void btnRename_Click(object sender, EventArgs e)
        {
            if (lstRenameFiles.Items.Count == 0)
            {
                MessageBox.Show("请选择要改名的文件！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            string dir = ddlDir.Text;

            int errorCount = 0;
            List<string> errorFileNames = new List<string>();

            for (int i = 0; i < lstRenameFiles.Items.Count; i++)
            {
                string originalFileName = dir + "\\" + lstRenameFiles.Items[i];
                string newFileName = originalFileName.Replace(txtOriginal.Text, txtNew.Text);
                try
                {
                    File.Move(originalFileName, newFileName);
                }
                catch (Exception e1)
                {
                    errorFileNames.Add(originalFileName);
                    MessageBox.Show("出现第 " + ++errorCount + " 个错误：" + e1.Message, "批量改名时出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            if (errorFileNames.Count != 0)
            {
                MessageBox.Show("共有 " + errorCount + " 个文件没有改名，分别为：" + string.Join(", ", errorFileNames.ToArray()));
            }

            MessageBox.Show("本次你已经更改了 " + (lstRenameFiles.Items.Count - errorCount) + " 个文件名。", "改名完成", MessageBoxButtons.OK, MessageBoxIcon.Information);

            AppendFileToList();
        }

        private void ddlDir_TextUpdate(object sender, EventArgs e)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(ddlDir.Text);

            if (directoryInfo.Exists)
            {
                AppendFileToList();
            }
        }

        private void AppendFileToList()
        {
            lstAllFiles.Items.Clear();
            lstRenameFiles.Items.Clear();

            string filter = ddlFilter.Text.Substring(ddlFilter.Text.IndexOf("(") + 1);
            filter = filter.Substring(0, filter.Length - 1);

            FileInfo[] files = GetFiles(ddlDir.Text, filter);

            for (int i = 0; i < files.Length; i++)
            {
                string fileName = files[i].Name;
                string fileSize = files[i].Length.ToString();
                string fileType = fileName.Substring(fileName.IndexOf(".") + 1);
                string fileModify = files[i].LastWriteTime.ToString("yyyy-MM-dd hh:mm:ss");
                lstAllFiles.Items.Add(new ListViewItem(new string[] { fileName, fileSize, fileType, fileModify }));
            }
        }

        private FileInfo[] GetFiles(string dir, string filter)
        {
            List<FileInfo> list = new List<FileInfo>();

            DirectoryInfo directoryInfo = new DirectoryInfo(dir);

            string[] filters = filter.Split(',');

            for (int i = 0; i < filters.Length; i++)
            {
                FileInfo[] fileInfos = directoryInfo.GetFiles(filters[i].Trim());
                list.AddRange(fileInfos);
            }

            //            list.Sort();

            return list.ToArray();
        }

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            lstRenameFiles.Items.Clear();

            for (int i = 0; i < lstAllFiles.Items.Count; i++)
            {
                lstRenameFiles.Items.Add((lstAllFiles.Items[i]).SubItems[0].Text);
            }

            lblRenameFilesCount.Text = lstRenameFiles.Items.Count.ToString();
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            lstRenameFiles.Items.Remove(lstRenameFiles.SelectedItem);

            lblRenameFilesCount.Text = lstRenameFiles.Items.Count.ToString();
        }

        private void btnRemoveAll_Click(object sender, EventArgs e)
        {
            lstRenameFiles.Items.Clear();

            lblRenameFilesCount.Text = lstRenameFiles.Items.Count.ToString();
        }

        private void ddlFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            AppendFileToList();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (lstAllFiles.SelectedItems.Count == 0)
            {
                MessageBox.Show("你还没有选择任何文件");
            }

            for (int i = 0; i < lstAllFiles.SelectedItems.Count; i++)
            {
                string fileName = lstAllFiles.SelectedItems[i].SubItems[0].Text;
                if (!lstRenameFiles.Items.Contains(fileName))
                {
                    lstRenameFiles.Items.Add(fileName);
                }

            }
        }

        private void btnOpenDir_Click(object sender, EventArgs e)
        {
            if(dgOpenDir.ShowDialog() == DialogResult.OK)
            {
                ddlDir.Text = dgOpenDir.SelectedPath;
                AppendFileToList();
            }
        }

        private void ddlDir_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                lstAllFiles.Focus();
                e.Handled = true;
            }
        }

        private void lstAllFiles_Click(object sender, EventArgs e)
        {
            if (lstAllFiles.SelectedItems.Count == 1)
            {
                picPreview.ImageLocation = ddlDir.Text + "\\" + lstAllFiles.SelectedItems[0].SubItems[0].Text;
            }
        }

        private void lstAllFiles_DoubleClick(object sender, EventArgs e)
        {
            if (lstAllFiles.SelectedItems.Count == 1)
            {
                string fileName = lstAllFiles.SelectedItems[0].SubItems[0].Text;
                if (!lstRenameFiles.Items.Contains(fileName))
                {
                    lstRenameFiles.Items.Add(fileName);
                }
            }
        }
    }
}
